const express = require('express')
const authenticateToken = require('../utils/authMiddleware.js') // 引入身份验证中间件
const xlsx = require('xlsx')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath, createExcelFileIfNotExists } = require('../utils/constants.js') // 引入常量

const router = express.Router()
// 使用绝对路径
const usersFilePath = getFilePath('users')
const followersFilePath = getFilePath('followers')

// 查询用户粉丝列表接口 (需要身份验证)
router.get('/getFollowers', authenticateToken, (req, res) => {
  const { userId } = req.query
  const currentUserId = req.user.id // 当前登录用户的ID

  const searchUserId = userId || currentUserId

  const followersWorkbook = xlsx.readFile(followersFilePath)
  const followersWorksheet = followersWorkbook.Sheets['followers']
  const followersData = xlsx.utils.sheet_to_json(followersWorksheet)

  // 查找指定用户的粉丝
  const userFollowers = followersData.filter((follow) => follow.UserID === searchUserId)

  // 获取粉丝的详细信息
  const usersWorkbook = xlsx.readFile(usersFilePath)
  const usersWorksheet = usersWorkbook.Sheets['users']
  const usersData = xlsx.utils.sheet_to_json(usersWorksheet)

  const followerIds = userFollowers.map((follow) => follow.FollowerID)
  const followerDetails = usersData.filter((user) => followerIds.includes(user.ID))

  return sendResponse(res, 200, followerDetails, '获取粉丝列表成功。')
})

module.exports = router
